/*
Audica Uploader - application for convenient uploading to various file hostings
Copyright (C) 2011-2012 Makarov Andrey (Winand)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "zhttpmultipart.h"
#include <QFileInfo>

ZHttpMultiPart::ZHttpMultiPart(QObject *parent) :
    Charsetter(parent)
{

}

QByteArray ZHttpMultiPart::convName(QString str) {
    return strConv('"' + str + '"', cs_names);
}

QByteArray ZHttpMultiPart::convValue(QString str) {
    return strConv('"' + str + '"', cs_values);
}

bool ZHttpMultiPart::appendField(const QString name, const QString value) {
    if(name.isEmpty() || value.isEmpty()) return false; //check
    QHttpPart part;
    part.setHeader(QNetworkRequest::ContentDispositionHeader,
                   QVariant("form-data; name=" + convName(name)));
    part.setBody(convValue(value));
    MultiPart.append(part);
    parts.append(name);
    return true;
}

bool ZHttpMultiPart::appendFile(const QString name, const QString path, const QString contentType) {
    if(name.isEmpty() || path.isEmpty() || contentType.isEmpty()) return false; //check
    QHttpPart part;
    QString filename = QFileInfo(path).fileName();
    part.setHeader(QNetworkRequest::ContentDispositionHeader,
                   QVariant("form-data; name=" + convName(name) + "; filename=" + convValue(filename)));
    part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType.toLatin1()));
    QFile* file = new QFile(path);
    if(file->open(QIODevice::ReadOnly)) {
        file->setParent(this); //will be destroyed along with this object
        part.setBodyDevice(file);
        MultiPart.append(part);
        parts.append(name);
        return true;
    } else delete file;
    return false;
}

bool ZHttpMultiPart::hasPart(const QString name) {
    return parts.contains(name);
}

void ZHttpMultiPart::setContentType(ZHttpMultiPart::ContentType ct) {
    if(inEnum(ct, "ContentType"))
        MultiPart.setContentType((QHttpMultiPart::ContentType)ct);
    else qDebug() << "ZHttpMultiPart::setContentType" << "Unknown content type" << ct;
}
